package postpc.powerreminders.com.systemEvents;

import postpc.powerreminders.com.db.RotgDatabase;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class IncomingCallReceiver extends BroadcastReceiver {

	/*
	 * Logger tag
	 */
	private static final String TAG = "ROTG_SYS_EVENTS";

	private static final int PHONE_REMINDER_TIME = 10000;
	
	/*
	 * Reference to the data base.
	 */	
	static RotgDatabase dataBase;

	public IncomingCallReceiver(){
		super();
	}
	
	/**
	 * 
	 * @param db
	 */
	public IncomingCallReceiver (RotgDatabase db){
		super();
		IncomingCallReceiver.dataBase = db;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();

		if(null == bundle)
			return;

		Log.i(TAG, bundle.toString());

		String state = bundle.getString(TelephonyManager.EXTRA_STATE);

		if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
		{
			String phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
			Log.i(TAG, "Incomng Number: " + phonenumber);
			Cursor cursor;
			try{
				cursor =IncomingCallReceiver.dataBase.checkCallEvent(phonenumber);
			} catch (Exception e){
				Log.e(TAG, "ERROR:" + e.getMessage());
				return;
			}
			// ALERT
			if (0 != cursor.getCount()){
				Log.i(TAG, "Incomng Number Message : " + cursor.getString(2));
				Toast notification = Toast.makeText(context, cursor.getString(2), Toast.LENGTH_LONG);
				notification.setDuration(PHONE_REMINDER_TIME);
				notification.show();
				dataBase.deactivateReminder(cursor.getInt(0));
			} else {
				Log.i(TAG, "No entry in the database : " + cursor.getString(2));
			}
		}
	}
}